﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Game;
using MyGame;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Windows;

namespace Menu
{
    public class LevelsPanel : ShowHidable
    {
        [SerializeField] private RectTransform _content;
        [SerializeField] private LevelTileUI _levelTileUIPrefab;
        [SerializeField] private Text _titleTxt;
        private readonly List<LevelTileUI> _tiles = new List<LevelTileUI>();
        private LevelGroup _levelGroup;     

        public LevelGroup LevelGroup
        {
            get => _levelGroup;
            set
            {
                _levelGroup = value;
                Match match = Regex.Match(value.name, @"\d+");  // 匹配数字
                _titleTxt.text = "关卡组 "+match;
                UpdateTiles();
            }
        }

   

        public void Back()
        {
            Hide();
        }

        public override void Show(bool animate = true, Action completed = null)
        {
           

            base.Show(animate, completed);
        }
        
        private void UpdateTiles()
        {
            var levels = LevelGroup.levels.ToList();
            while (_tiles.Count < levels.Count)
            {
                var levelTileUI = Instantiate(_levelTileUIPrefab, _content);
                
                levelTileUI.Clicked += LevelTileUIOnClicked;
                _tiles.Add(levelTileUI);
            }

            while (_tiles.Count > levels.Count)
            {
                Destroy(_tiles.Last().gameObject);
                _tiles.RemoveAt(_tiles.Count-1);
            }

            for (var i = 0; i < levels.Count; i++)
            {
                _tiles[i].Level = levels[i];
                _tiles[i].CurrentStatus = ResourceManager.GetCompletedLevel(LevelGroup.id) >= levels[i].LevelNo
                    ?
                    LevelTileUI.Status.Completed
                    : ResourceManager.IsLevelLocked(LevelGroup.id, levels[i].LevelNo)
                        ? LevelTileUI.Status.Locked
                        : LevelTileUI.Status.Unlocked;
            }
        }

        private void LevelTileUIOnClicked(LevelTileUI tile)
        {
            if (ResourceManager.GetCompletedLevel(LevelGroup.id)+1 >= tile.Level.LevelNo)
            {
                GameManager.LoadGame(new LoadGameDetails
                {
                    GameType = GameType.Normal,
                    LevelGroup = LevelGroup,
                    Level = tile.Level.LevelNo
                });
            }

        }
    }
}